﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MAPDavy.Entities;
using MAPDavy.BusinessLogic;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using MvcSiteMapProvider;
using MAPDavy.WebMVC3.ViewModels;
using MAPDavy.WebMVC3.Models;

namespace MAPDavy.WebMVC3.Controllers
{
    public class TermController : Controller
    {
        public TermController()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                container.BuildUp(this.GetType(), this);
            }
        }

        [Dependency]
        public ITermBL  TermBL { get; set; }

        [Dependency]
        public IAnioLectivoBL AnioLectivoBL { get; set; }

        [Dependency]
        public ISubjectBL  SubjectBL { get; set; }

        [Dependency]
        public IGradeBL GradeBL { get; set; }

        [Dependency]
        public IMAPBL MAPBL { get; set; }
        //
        // GET: /Term/
        [Authorize(Roles = "admin,editor")]
        public ActionResult Index(Int32 anio = 0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                anio = Int32.Parse(cookie.Value.ToString());
            }  

            var terms = TermBL.GetFromTermByAnio(anio.ToString());  

            return View(terms);
        }

        //
        // GET: /Term/Details/5
        [Authorize(Roles = "admin,editor")]
        public ActionResult Details(int id)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        //
        // GET: /Term/Create
        [Authorize(Roles = "admin")]
        public ActionResult Create()
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            //var anio = Int32.Parse(cookie.Value.ToString());

            //var terms = TermBL.GetFromTermByAnio(anio.ToString()).Select(t=>t.MapId).ToArray();  
            var maps = MAPBL.GetAllFromMAP();

            ViewData["MapId"] = new SelectList(maps, "Id", "NameMap");

            return View();
        } 

        //
        // POST: /Term/Create

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                var cookie = Request.Cookies["workspace"];

                if (cookie == null)
                {
                    return RedirectToAction("Index", "Home");
                }

                Term term = new Term()
                {
                    MapId = Int32.Parse(collection["MapId"].ToString()),
                    NameTerm = collection["NameTerm"].ToString(),
                    Description = collection["Description"].ToString(),
                    Anio = cookie.Value.ToString()                     
                };

                var fechaIni = collection["TestingStartDate"].ToString();
                var fechaFin = collection["TestingEndDate"].ToString();

                if (fechaIni != string.Empty) term.TestingStartDate = DateTime.Parse(fechaIni);
                if (fechaFin != string.Empty) term.TestingEndDate = DateTime.Parse(fechaFin);

                var isCerrado = collection["Cerrado"].ToString();

                term.Cerrado = isCerrado == "false" ? false : true;

                if (term.Anio != cookie.Value.ToString() )
                {
                    return RedirectToAction("Index", "Term");
                }

                TermBL.AddTerm(term);  

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult ValidateMAP(int mapId)
        {

                var cookie = Request.Cookies["workspace"];

                var  anio = Int32.Parse(cookie.Value.ToString());             

                var terms = TermBL.GetFromTermByAnio(anio.ToString());

                var existe = (from t in terms
                              where t.MapId == mapId
                              select t).SingleOrDefault();

                if (existe == null)
                    return Json(true, JsonRequestBehavior.AllowGet);
                else
                    return Json(false, JsonRequestBehavior.AllowGet);
                
        }

        //
        // GET: /Term/Edit/5
        [MvcSiteMapNode(Title = "Modificar Evaluación", ParentKey = "term", Order=1)]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id=0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (id == 0)
            {
                return RedirectToAction("Index", "Term");
            }

            var term = TermBL.GetFromTermById(id);

            if (term == null)
            {
                return RedirectToAction("Index", "Term");
            }

            if (term.Anio != cookie.Value.ToString())
            {
                return RedirectToAction("Index", "Term");
            }

            return View(term);
        }

        [MvcSiteMapNode(Title = "Secciones", ParentKey = "term",Key="rit",Order=3)]
        [Authorize(Roles = "admin,editor")]
        public ActionResult ChooseSection(int id=0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (id == 0)
            {
                return RedirectToAction("Index", "Term");
            }

            var term = TermBL.GetFromTermById(id);

            if (term== null)
            {
                return RedirectToAction("Index", "Term");
            }

            var grades = GradeBL.GetFromGradeByTermId(id);

            if (term.Anio != cookie.Value.ToString() )
            {
                return RedirectToAction("Index", "Term");
            }

            var tgVM = new TermGradesViewModel() 
            {
                Term = term,
                Grades = grades
            };

            return View(tgVM);
        }

        //
        // POST: /Term/Edit/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                var cookie = Request.Cookies["workspace"];

                if (cookie == null)
                {
                    return RedirectToAction("Index", "Home");
                }               

                Term term = new Term()
                {
                    Id = Int32.Parse(collection["Id"].ToString() ),  
                    NameTerm = collection["NameTerm"].ToString(),
                    Description = collection["Description"].ToString(),
                    Anio = collection["Anio"]
                };

                var fechaIni = collection["TestingStartDate"].ToString();
                var fechaFin = collection["TestingEndDate"].ToString();

                if (fechaIni != string.Empty) term.TestingStartDate = DateTime.Parse(fechaIni);
                if (fechaFin != string.Empty) term.TestingEndDate = DateTime.Parse(fechaFin);

                if (term.Anio != cookie.Value.ToString())
                {
                    return RedirectToAction("Index", "Term");
                }

                var isCerrado = collection["Cerrado"].ToString();

                term.Cerrado = isCerrado == "false" ? false : true;
                
                TermBL.UpdateTerm(term) ;  
 
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        //
        // GET: /Term/Delete/5
 
        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        //
        // POST: /Term/Delete/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult CanDeleteServiceJson(int id)
        {
            var can = TermBL.CanRemoveTerm(id);

            return Json(can, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                TermBL.RemoveTerm(id);  

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        [MvcSiteMapNode(Title = "Configurar Evaluación", ParentKey = "term",Order=2)]
        [Authorize(Roles = "admin")]
        public ActionResult ConfigTerm(int id=0)
        {
            var cookie = Request.Cookies["workspace"];
            
            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (id == 0)
            {
                return RedirectToAction("Index", "Term");
            }

            var term = TermBL.GetFromTermById(id);

            if (term == null)
            {
                return RedirectToAction("Index", "Term");
            }

            if (term.Anio != cookie.Value.ToString())
            {
                return RedirectToAction("Index", "Term");
            }

            if (term.Cerrado)
            {
                return RedirectToAction("Index", "Term");
            }

            var grades = GradeBL.GetAllFromGrade();
            var subjects = SubjectBL.GetAllFromSubject();   

            ViewData["Grade"] = new SelectList(grades, "Id", "GradeLevel");
            ViewData["Subject"] = new SelectList(subjects, "Id", "NameSubject");

            return View(term);
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult AsignarTest(int termId,int gradeId,int testId, string anio)
        {
            try
            {
                var testGrade = new TestGrade() 
                {
                    TermId = termId,
                    GradeId = gradeId,
                    TestId = testId,
                    Anio = anio 
                };

                TermBL.AddTestGrade(testGrade);
 
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        //[HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult RemoveTestGrade(int termId, int gradeId, int testId)
        {
            try
            {
                var testGrade = new TestGrade()
                {
                    TermId = termId,
                    GradeId = gradeId,
                    TestId = testId,
                };

                var result = TermBL.CanRemoveTestGrade(testGrade);

                if (result)
                {
                    TermBL.RemoveTestGrade(testGrade);
 
                    var msg = new { rtp=true,text="Se Quito Correctamente" };

                    return Json(msg, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var msg = new { rtp = false, text = "No se Puede Quitar el Item(s) Seleccionado(s) proque tiene Información Asociada" };
                    return Json(result, JsonRequestBehavior.AllowGet);
                }               

            }
            catch
            {
                var msg = new { rtp = false, text = "Hubo problemas al quitar el Item(s) Seleccionado(s)" };
                return Json(msg, JsonRequestBehavior.AllowGet);
            }
                
        }

        public ActionResult CreateExcel(Int32 id=0)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (id == 0)
            {
                return RedirectToAction("Index", "Term");
            }

            var term = TermBL.GetFromTermById(id);

            if (term == null)
            {
                return RedirectToAction("Index", "Term");
            }

            var templates = TermBL.GetFromCRFTemplateByTermId(id);

            var nameFile= string.Format("MAP {0} {1} - {2}.xlsx",term.MAP.NameMap,term.Anio,term.NameTerm);

            return File(CRFTemplateExcel.CreateExcel(templates), "application/vnd.xls",nameFile );
        }
    }
}
